import { Component, Fragment } from 'react'; // 占位符
import { CSSTransition } from 'react-transition-group'; // 动画组件
import TodoItem from './TodoItem';
import axios from 'axios';

class TodoList extends Component {
    constructor(props) {
        // 当组件的state或props发生改变的时候，rander函数就会重新执行
        // 当父组件的render函数重新执行时，子组件的rander函数也会被重新执行
        super(props);
        this.state = {
            value: '',
            list: [],
            show: true,
        };
    }
    render() {
        return (
            <Fragment>
                {/* todolist */}
                <div>
                    <label htmlFor="input">输入内容</label>
                    <input id="input" type="text" value={this.state.value} onChange={this.change.bind(this)} />
                    <button onClick={this.addClick.bind(this)} className="btn">
                        提交
                    </button>
                </div>
                <ul>{this.getTodoItem()}</ul>
                <div>
                    <CSSTransition in={this.state.show} timeout={1000} appear={true} unmountOnExit classNames="mydemo">
                        <p>hello</p>
                    </CSSTransition>
                    <button onClick={this.toggle.bind(this)}>提交</button>
                </div>
            </Fragment>
        );
    }
    toggle() {
        this.setState(() => ({
            show: !this.state.show,
        }));
    }
    componentDidMount() {
        // 处理axios异步请求
        axios
            .get('https://www.fastmock.site/mock/0764b93cba70add273910b232c51aad8/development/api/getHotList')
            .then(function (res) {
                console.log(res.data);
            })
            .catch(function (err) {
                console.log(err);
            });
    }
    getTodoItem() {
        return this.state.list.map((item, index) => {
            // 父组件传递属性和方法到子组件
            // return <li key={index} onClick={this.delClick.bind(this, index)} dangerouslySetInnerHTML={{ __html: item }}></li>;
            return <TodoItem content={item} index={index} key={index} delItem={this.delClick.bind(this)} />;
        });
    }
    change(e) {
        // this.setState({
        //     value: e.target.value,
        // });

        // 新版写法 推荐
        this.setState(() => ({
            value: e.target.value,
        }));
    }
    addClick() {
        this.setState({
            list: [...this.state.list, this.state.value],
            value: '',
        });
    }
    delClick(index) {
        let list = [...this.state.list];
        list.splice(index, 1);
        this.setState({
            list,
        });
    }
}

export default TodoList;
